//
//  SNOxChartView.m
//  project
//
//  Created by 黄建华 on 2017/12/8.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNOxChartView.h"
#define LEFTWIDTH     30.0
#define SNOXCOLORDEEP [UIColor colorFromHex:0xf9339c]
@implementation SNOxChartView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
       [self performSelector:@selector(createChartView) withObject:nil afterDelay:IOSINITWAITTIME];
    }
    return self;
}

- (void)createChartView {
    self.backgroundColor = [UIColor whiteColor];
}

- (void)UpdateViewWithType:(SelectDateType)type withArray:(NSArray *)dataArray {
    [self loadBackgroundLayer];
    //数据加载
    NSMutableArray *array = [NSMutableArray array];
    if (type == 0) {
        array = [NSMutableArray arrayWithArray:dataArray];
    } else if (type == 1) {
        array = [NSMutableArray arrayWithArray:dataArray];
    } else if (type == 2) {
        array = [NSMutableArray arrayWithArray:dataArray];
    } else if (type == 3) {
        for (int i = 0; i < 12; i++) {
            [array addObject:@(arc4random()%10 +90)];
        }
    }
    
    _selectDateLabel               = [[SNCustomLabel alloc] initWithFrame:CGRectMake(-20, 10, 200, 20)];
    _selectDateLabel.textAlignment = NSTextAlignmentLeft;
    _selectDateLabel.textColor     = SNCOLORBLACK;
    _selectDateLabel.font          = SNSFONT(14.0);
    [_chartView addSubview:_selectDateLabel];
    
    //    _valueLabel = [[SNCustomLabel alloc] initWithFrame:CGRectMake(HHHWIDTH - 205, 10, 200, 20)];
    //    _valueLabel.textAlignment = NSTextAlignmentRight;
    //    _valueLabel.textColor = SNCOLORBLACK;
    //    _valueLabel.font = SNSFONT(13.0);
    //    [_chartView addSubview:_valueLabel];
    //    _valueLabel.text = [NSString stringWithFormat:@"%@    %ld  ",SN_Text(@"Total steps:"),(long)model.step];
    
    _unitLabel               = [[SNCustomLabel alloc] initWithFrame:CGRectMake(10, self.height - 30, self.width - 20, 15)];
    _unitLabel.textColor     = SNCOLORGRAY;
    _unitLabel.font          = SNFONT(10.0);
    _unitLabel.textAlignment = NSTextAlignmentLeft;
    [_chartView addSubview:_unitLabel];
    
    UIView *lineGray0 = [[UIView alloc] init];
    lineGray0.backgroundColor = SNCOLORWITHHEX(0xd7d8d9);
    lineGray0.frame           = SNFRAME(5, _chartView.origin.y + 50, 1, _chartView.height - 90);
    [_chartView addSubview:lineGray0];
    
    NSArray *qualityArray = [[NSArray alloc] initWithObjects:@"90", @"92", @"94", @"96", @"98", @"100", nil];
    for (int i = 0; i < 6; i++) {
        SNCustomLabel *label = [[SNCustomLabel alloc] initWithFrame:CGRectMake(-LEFTWIDTH -3, _chartView.origin.y + 42 + i*(_chartView.height - 90 + FitSimpleSize(12, 16, 24, 28, 36))/6, 30, 20)];
        label.textAlignment = NSTextAlignmentRight;
        label.textColor     = SNCOLORBLACK;
        label.font          = SNSFONT(9.0);
        label.text          = [qualityArray objectAtIndex:5 -i];
        [_chartView addSubview:label];
        
        if (i < 5) {
            UIView *line = [[UIView alloc] init];
            line.frame           = SNFRAME(5, label.center.y, self.width - 10, 0.5);
            line.backgroundColor = SNCOLORWITHHEX(0xd7d8d9);
            line.alpha           = 0.33;
            [_chartView addSubview:line];
        }
    }
    
    UIView *lineGray = [[UIView alloc] init];
    lineGray.backgroundColor = SNCOLORWITHHEX(0xd7d8d9);
    lineGray.frame           = SNFRAME(5, self.height - 40, self.width - 10, 1);
    [_chartView addSubview:lineGray];
    
    if (type == 0) {
        _selectDateLabel.text = [SN_PublicClass.selectDate dateToSelectDateShow];
    } else {
        _selectDateLabel.text = [SN_PublicClass showDateWithType:type];
    }
    
    NSInteger maxValue = 10;
    NSInteger minValue = 0;
    
    float   Origin_x      = 10;
    CGFloat Origin_height = self.height - 40;
    CGFloat offsetY       = FitScreenNumber(40, 40, 40, 40, 40);
    float   max           = 0;
    
    for (int i = 0; i < array.count; i++) {
        CGFloat value = [[array objectAtIndex:i] floatValue] - 90;
        if (value > maxValue) {
            value = maxValue;
        }
        
        CGFloat height = 0;
        CGFloat h      = (self.height - (25 + 30 + offsetY)) * (value / maxValue);
        if (isnan(h)) {
            height = 0;
        } else {
            height = h;
        }
        static int total = 0;
        total = total + value;
        
        CGFloat chartWidth = 0;
        CGFloat chartSpace = 0;
        if (type == 0) {
            chartWidth = 2.5;
            chartSpace = (self.width - Origin_x *2)/96;
        } else if (type == 1) {
            Origin_x   = 20;
            chartWidth = 5;
            chartSpace = (self.width - Origin_x *2)/7 + 5;
        } else if (type == 2) {
            chartWidth = 3;
            chartSpace = (self.width - Origin_x *2)/31;
        } else if (type == 3) {
            chartWidth = 3;
            chartSpace = (self.width - Origin_x *2)/12 + 1.5;
        }
        
        CGPoint point01 = CGPointMake(i * chartSpace + Origin_x - LEFTWIDTH, Origin_height - height);
        CGPoint point02 = CGPointMake((i) * chartSpace + Origin_x +chartWidth - LEFTWIDTH, Origin_height - height);
        
        UIBezierPath *fill = [UIBezierPath bezierPath];
        [fill moveToPoint:point01];
        [fill addLineToPoint:point02];
        [fill addLineToPoint:CGPointMake(point02.x, Origin_height)];
        [fill addLineToPoint:CGPointMake(point01.x, Origin_height)];
        
        // 填充区域
        CAShapeLayer *fillLayer = [CAShapeLayer layer];
        fillLayer.frame       = self.bounds;
        fillLayer.bounds      = self.bounds;
        fillLayer.path        = fill.CGPath;
        fillLayer.strokeColor = SNOXCOLORDEEP.CGColor;
        fillLayer.fillColor   = SNOXCOLORDEEP.CGColor;
        fillLayer.lineWidth   = 0.0;
        fillLayer.lineJoin    = kCALineJoinRound;
        [_backGroundLayer addSublayer:fillLayer];
        
        UIBezierPath *noFill = [UIBezierPath bezierPath];
        [noFill moveToPoint:CGPointMake(point01.x, Origin_height)];
        [noFill addLineToPoint:CGPointMake(point02.x, Origin_height)];
        [noFill addLineToPoint:CGPointMake(point02.x, Origin_height)];
        [noFill addLineToPoint:CGPointMake(point01.x, Origin_height)];
        
        // 填充区域过渡动画
        CABasicAnimation *fillAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
        fillAnimation.duration       = SNACTIONTIME;
        fillAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        fillAnimation.fillMode       = kCAFillModeForwards;
        fillAnimation.fromValue      = (id)noFill.CGPath;
        fillAnimation.toValue        = (id)fill.CGPath;
        [fillLayer addAnimation:fillAnimation forKey:@"path"];
        
        //圆角
        UIView *view = [[UIView alloc] init];
        view.frame               = SNFRAME(point01.x + LEFTWIDTH, point01.y, chartWidth, height == 0 ? 0 : 5);
        view.backgroundColor     = SNOXCOLORDEEP;
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius  = chartWidth/2;
        [_chartView addSubview:view];
        view.alpha = 0.0;
        
        dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SNACTIONTIME * NSEC_PER_SEC));
        void            (^task)() = ^{
            view.alpha = 1.0;
            view.frame = SNFRAME(point01.x + LEFTWIDTH, point01.y - 2.5, chartWidth, 5);
            if (value == 0) {
                view.alpha = 0.0;
            }
        };
        // 经过多少纳秒，由主队列调度任务异步执行
        dispatch_after(when, dispatch_get_main_queue(), task);
        
        if (type == 0) {
            NSArray       *weekArray = [[NSArray alloc] initWithObjects:@"00:00", @"04:00", @"08:00", @"12:00", @"16:00", @"20:00", @"23:59", nil];
            SNCustomLabel *label     = [[SNCustomLabel alloc] initWithFrame:CGRectMake(0, self.height - 30, 100, 20)];
            label.center        = CGPointMake(view.center.x + 2.0, self.height - 25);
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor     = SNCOLORBLACK;
            label.font          = SNSFONT(9.0);
            [_chartView addSubview:label];
            int num = 0;
            if (array.count == 48) {
                num = 8;
            }
            if (array.count == 96) {
                num = 16;
            }
            if (i % num == 0) {
                label.text = [weekArray objectAtIndex:i/num];
            }
            if (i == array.count - 1) {
                label.text   = [weekArray objectAtIndex:6];
                label.center = CGPointMake(view.center.x - 2.0, self.height - 25);
            }
        }
        
        if (type == 1) {
            NSArray       *weekArray = [[NSArray alloc] initWithObjects:SN_Text(@"周日"), SN_Text(@"周一"), SN_Text(@"周二"), SN_Text(@"周三"), SN_Text(@"周四"), SN_Text(@"周五"), SN_Text(@"周六"), nil];
            SNCustomLabel *label     = [[SNCustomLabel alloc] initWithFrame:CGRectMake(0, self.height - 30, 100, 20)];
            label.center        = CGPointMake(view.center.x, self.height - 25);
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor     = SNCOLORBLACK;
            label.font          = SNSFONT(10.0);
            label.text          = [weekArray objectAtIndex:i];
            [_chartView addSubview:label];
        }
        if (type == 2) {
            SNCustomLabel *label = [[SNCustomLabel alloc] initWithFrame:CGRectMake(0, self.height - 30, 100, 20)];
            label.center        = CGPointMake(view.center.x, self.height - 25);
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor     = SNCOLORBLACK;
            label.font          = SNSFONT(10.0);
            [_chartView addSubview:label];
            if (i == 0 || i == 4 || i == 9 || i == 14 || i == 19 || i == 24 || i == 29) {
                label.text = StrByInt(i+1);
            } else {
                label.text = @".";
            }
        }
        //        if (type == 3)
        //        {
        //            SNCustomLabel *label = [[SNCustomLabel alloc] initWithFrame:CGRectMake(0, self.height - 30, 100, 20)];
        //            label.center = CGPointMake(view.center.x, self.height - 25);
        //            label.textAlignment = NSTextAlignmentCenter;
        //            label.textColor = SNCOLORBLACK;
        //            label.font = SNSFONT(10.0);
        //            label.text = StrByInt(i+1);;
        //            [_chartView addSubview:label];
        //        }
    }
}

- (void)loadBackgroundLayer {
    if (_chartView) {
        [_chartView removeFromSuperview];
        _chartView = nil;
    }
    
    _chartView                 = [[UIView alloc] init];
    _chartView.backgroundColor = [UIColor whiteColor];
    _chartView.frame           = CGRectMake(0, 0, self.width, self.height);
    [self addSubview:_chartView];
    
    if (_backGroundLayer) {
        [_backGroundLayer removeFromSuperlayer];
        _backGroundLayer = nil;
    }
    _backGroundLayer                 = [CALayer layer];
    _backGroundLayer.backgroundColor = [UIColor clearColor].CGColor;
    _backGroundLayer.bounds          = CGRectMake(0, 0, self.width, self.height);
    _backGroundLayer.position        = CGPointMake(self.center.x, self.height / 2);
    [_chartView.layer addSublayer:_backGroundLayer];
}

- (NSInteger)max:(NSArray *)Array {
    if (Array.count == 0) {
        return 0;
    }
    
    NSInteger max = [[Array objectAtIndex:0] integerValue];
    
    for (int i = 0; i < Array.count; i++) {
        if ([[Array objectAtIndex:i] integerValue] > max) {
            max = [[Array objectAtIndex:i] integerValue];
        }
    }
    
    return max;
}

- (NSInteger)min:(NSArray *)Array {
    if (Array.count == 0) {
        return 0;
    }
    
    NSInteger min = [[Array objectAtIndex:0] integerValue];
    
    for (int i = 0; i < Array.count; i++) {
        if ([[Array objectAtIndex:i] integerValue] < min) {
            min = [[Array objectAtIndex:i] integerValue];
        }
    }
    return min;
}

@end

